import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_give/pages/personal/personal_vm.dart';
import 'package:flutter_give/route/route_utils.dart';
import 'package:flutter_give/route/routes.dart';
import 'package:flutter_give/utils/LogUtils.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:oktoast/oktoast.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:provider/provider.dart';
import 'package:rapid_kit/rapid_kit.dart';

import '../../common_ui/dialog/dialog_title.dart';
import '../../repository/api.dart';
import '../../utils/constants.dart';
import '../../utils/sp_utils.dart';
import '../Home/home_vm.dart';
import '../subpackage/saveusername.dart';

/// 我的页面
class PersonalPage extends StatefulWidget {
  const PersonalPage({super.key});

  @override
  State<StatefulWidget> createState() {
    return PersonalPageState();
  }
}

class PersonalPageState extends State<PersonalPage> {
  PersonViewModel viewModel = PersonViewModel();

  static final GlobalKey<PersonalPageState> globalKeythere =
      GlobalKey<PersonalPageState>();

  String _versionNare = "";

  // 日志
  String _dailyrecord = "--";

  @override
  void initState() {
    super.initState();
    viewModel.initData();

    setSystemUIOverlayStyle();
    _getVersion();
  }

  // 重新加载
  void reloadData() {
    print("==============加载第三页数据=============");
    // 确保页面渲染完成后再执行 setSystemUIOverlayStyle
    WidgetsBinding.instance.addPostFrameCallback((_) {
      setSystemUIOverlayStyle();
      viewModel.initData();
    });
  }

  void setSystemUIOverlayStyle() {
    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarColor: Color(0xFFbdeddd),
      statusBarIconBrightness: Brightness.dark,
    ));
  }

  // 获取版本号 - 私有属性
  Future _getVersion() async {
    PackageInfo info = await PackageInfo.fromPlatform();
    // LogUtils.w(info);
    var version = info.version;
    _versionNare = "v $version";
    setState(() {});
  }


  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) {
        return viewModel;
      },
      child: Scaffold(
        appBar: AppBar(
          toolbarHeight: 45,
          title: Text(
            '',
            style: TextStyle(
              color: Color(0xFF454547),
              fontWeight: FontWeight.w600,
              fontSize: 20.sp,
              fontFamily: "PingFang SC",
            ),
          ),
          flexibleSpace: Container(
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topCenter, // 从顶部开始
                end: Alignment.bottomCenter, // 到底部结束
                colors: [Color(0xFFbdeddd), Color(0xFFdaece9)], // 渐变颜色
              ),
            ),
          ),
          elevation: 20,
        ),
        body: SafeArea(
          child: Container(
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage('assets/app_img/one.png'), // 替换为你的图片路径
                fit: BoxFit.cover, // 设置图片的填充方式
              ),
            ),
            child: Container(
              width: double.infinity,
              color: Color(0xFFF1F1F1).withOpacity(0.8),
              // 设置背景颜色为 #f1f1f1，并添加透明度
              padding: EdgeInsets.only(top: 10, left: 15, right: 15, bottom: 0),
              child: Column(
                children: [
                  _minititle(),
                  SizedBox(height: 30), // 添加一些间距
                  _buildRow()
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildRow() {
    return Consumer<PersonViewModel>(builder: (context, vm, child) {
      return Container(
        decoration: BoxDecoration(
          color: Colors.white, // 设置白色背景
          borderRadius: BorderRadius.circular(12.0), // 设置圆角
          border: Border.all(
            color: Color(0xFFf8f7f7), // 设置边框颜色
            width: 1.0, // 设置边框宽度
          ),
        ),
        padding: EdgeInsets.only(
          top: 7, // 上边距
          bottom: 7, // 下边距
          left: 5, // 左边距
          right: 0, // 右边距
        ),
        child: Column(
          children: [
            InkWell(
              onTap: () {
                // 设备数量点击事件
                print('设备数量被点击');
              },
              child: Container(
                padding: EdgeInsets.all(15.0), // 设置内边距
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Row(
                      children: [
                        Image.asset(
                          'assets/app_img/equipment.png', // 本地图片路径
                          width: 21, // 设置图片宽度
                          height: 21, // 设置图片高度
                        ),
                        SizedBox(width: 10),
                        Text(
                          '设备数量',
                          style: TextStyle(fontSize: 16),
                        ),
                      ],
                    ),
                    Text(
                      '${vm.eqdatalist ?? '0'}个设备',
                      style: TextStyle(fontSize: 16, color: Color(0xFF5a5a5a)),
                    ),
                  ],
                ),
              ),
            ),
            InkWell(
              onTap: () {
                // 帮助与反馈点击事件
                print('帮助与反馈被点击');
                RouteUtils.pushForNamed(context, RoutePath.FeedbackPage);
              },
              child: Container(
                padding: EdgeInsets.all(15.0), // 设置内边距
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Row(
                      children: [
                        Image.asset(
                          'assets/app_img/subscription.png', // 本地图片路径
                          width: 21, // 设置图片宽度
                          height: 24, // 设置图片高度
                        ),
                        SizedBox(width: 10),
                        Text(
                          '帮助与反馈',
                          style: TextStyle(fontSize: 16),
                        ),
                      ],
                    ),
                    Icon(Icons.arrow_forward_ios,
                        size: 16, color: Color(0xFF5a5a5a)),
                  ],
                ),
              ),
            ),
            InkWell(
              onTap: () {
                // APP版本点击事件
                print('APP版本被点击');
              },
              child: Container(
                padding: EdgeInsets.all(15.0), // 设置内边距
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Row(
                      children: [
                        Image.asset(
                          'assets/app_img/appversions.png', // 本地图片路径
                          width: 21, // 设置图片宽度
                          height: 24, // 设置图片高度
                        ),
                        SizedBox(width: 10),
                        Text(
                          'APP版本',
                          style: TextStyle(fontSize: 16),
                        ),
                      ],
                    ),
                    Text(_versionNare,
                        style:
                            TextStyle(fontSize: 16, color: Color(0xFF5a5a5a))),
                  ],
                ),
              ),
            ),
            InkWell(
              onTap: () {
                // 设置点击事件
                print('设置被点击');
                RouteUtils.pushForNamed(context, RoutePath.SettingPage);
              },
              child: Container(
                padding: EdgeInsets.all(15.0), // 设置内边距
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Row(
                      children: [
                        Image.asset(
                          'assets/app_img/install.png', // 本地图片路径
                          width: 21, // 设置图片宽度
                          height: 21, // 设置图片高度
                        ),
                        SizedBox(width: 10),
                        Text(
                          '设置',
                          style: TextStyle(fontSize: 16),
                        ),
                      ],
                    ),
                    Icon(Icons.arrow_forward_ios,
                        size: 16, color: Color(0xFF5a5a5a)),
                  ],
                ),
              ),
            ),
            InkWell(
              onTap: () async {
                // final resp = await Assistant.upload();
                //
                // if (resp.success) {
                //   LogUtils.w("=日志=>${resp.data}");
                //   setState(() {
                //     _dailyrecord = "${resp.data}";
                //   });
                // } else {
                //   // 处理失败情况
                // }
                Assistant.showEntry(context);
                // ignore: use_build_context_synchronously
                if (!context.mounted) return;
              },
              child: Container(
                padding: EdgeInsets.all(13.0), // 设置内边距
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      '获取日志${_dailyrecord}',
                      style: TextStyle(fontSize: 16),
                    ),
                    Row(
                      children: [
                        IconButton(
                          icon: Icon(Icons.content_copy, size: 16, color: Color(0xFF5a5a5a)),
                          onPressed: () {
                            Clipboard.setData(ClipboardData(text: _dailyrecord));
                            // 可以添加一个提示，告诉用户内容已复制
                            ScaffoldMessenger.of(context).showSnackBar(
                              SnackBar(content: Text('已复制到剪贴板')),
                            );
                          },
                        ),
                        Icon(Icons.arrow_forward_ios, size: 16, color: Color(0xFF5a5a5a)),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      );
    });
  }

  Widget _minititle() {
    return Consumer<PersonViewModel>(
      builder: (context, vm, child) {
        String maskedPhoneNumber = vm.usernamephone != null
            ? vm.usernamephone!.replaceRange(3, 7, '****')
            : "";

        return Row(
          children: [
            Image.asset(
              'assets/app_img/ic_launch.png', // 本地图片路径
              width: 50, // 设置图片宽度
              height: 50, // 设置图片高度
            ),
            SizedBox(width: 10), // 添加一些间距
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                GestureDetector(
                  onTap: () async {
                    print("上面的手机号码被点击了");
                    String name =
                        await SpUtils.getString(Constants.SP_USER_NAME);
                    Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) =>
                                SaveusernamePage(deviceName: name ?? "",)));

                    // DialogInputFactory.instancess.showuserDialog(context, name,
                    //     onComplete: (success, message, username) {
                    //   if (success) {
                    //     LogUtils.w("昵称= $username");
                    //
                    //   } else {
                    //     print("操作失败: $message");
                    //   }
                    // });
                  },
                  child: Text(
                    vm.username ?? "",
                    style: TextStyle(
                      fontSize: 18,
                      color: Colors.black,
                      fontFamily: "PingFang SC",
                    ),
                  ),
                ),
                SizedBox(height: 1), // 添加一些间距
                Text(
                  maskedPhoneNumber, // 下面的手机号码
                  style: TextStyle(
                      fontSize: 14,
                      fontFamily: "PingFang SC",
                      color: Colors.grey.shade700),
                ),
              ],
            ),
          ],
        );
      },
    );
  }
}
